﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DynamicDnsChanger.Extensions;
using System.ComponentModel.Composition;
using System.Text.RegularExpressions;
using System.Diagnostics.Contracts;
namespace DynamicDnsChanger.Extensions.CheckIP
{

    [Export(typeof(ICheckIP))]
    public class CheckIP : IPlugin, ICheckIP
    {
        private readonly IRequester _Requester;
        public string Name
        {
            get { return "CheckIP"; }
        }

        public event EventHandler<InfoStatus> StatusChange;
        [ImportingConstructor]
        public CheckIP(IRequester Requester)
        {
            Contract.Requires(Requester != null, "IRequester");
            this._Requester = Requester;
        }
        public void Check()
        {
            var sites = new string[] { 
                "http://checkip.mtgsy.net/", 
                "http://checkip.dyndns.org", 
                "http://www.checkip.org/", 
                "http://whatismyipaddress.com/",
                "http://ping.eu/",
                "http://www.myiponline.com/"
            };
            var IP = "";
            foreach (var site in sites)
            {
                try
                {
                    IP = ExtractIP(_Requester.GetString(site));
                    if (!String.IsNullOrEmpty(IP))
                    {
                        StatusChange.Invoke(this, new InfoStatus(
                            TypeOfMessage.Success,
                            IP
                        ));
                        break;
                    }
                }
                catch (Exception ex)
                {
                    
                    StatusChange.Invoke(this, new InfoStatus(
                            TypeOfMessage.Info,
                            String.Format("Erro consultando IP em {0} > {1}", site, ex.Message )
                        ));
                }
            }
        }

        private string ExtractIP(string p)
        {
            String IPADDRESS_PATTERN = "(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)";
            return Regex.Match(p, IPADDRESS_PATTERN).Groups[0].Value;
        }
    }
}
